import React, { useState } from 'react';
import { Select, Form, Space } from 'antd';
import NumberField from '../../../../components/common/NumberField';
import StatefulCalculationCard from '../../../../components/common/StatefulCalculationCard';
import ExportData from '../../../../components/common/ExportCalculateData';
import { ResultItem } from '../../../../../shared/types';

const { Option } = Select;

// 定义所有表单数据类型
export interface FormValues {
  // 通用选择项
  burial_type: string;      // 埋置类型：深埋、浅埋
  soil_mass: string;        // 土体类型：有限土体、无限土体
  slope_direction: string;  // 斜坡方向：上斜、下斜
  
  // 深埋无限参数
  varphi_c: number;         // 计算内摩擦角
  
  // 浅埋无限上斜参数
  alpha: number;            // 充填物表面与水平面夹角
  
  // 浅埋无限下斜参数
  phi: number;              // 内摩擦角
  
  // 浅埋有限上斜/下斜参数
  m: number;                // 填充物表面坡率
  n: number;                // 溶洞壁隧道填充物表面交叉点连线坡率
  mu: number;               // 溶腔壁充填物之间摩擦系数
  delta: number;            // 侧向土压力与水平线夹角
}

// 计算初始值配置
const initialValues: FormValues = {
  burial_type: '深埋',
  soil_mass: '无限土体',
  slope_direction: '上斜',
  varphi_c: 30.0,
  alpha: 10.0,
  phi: 30.0,
  m: 1.0,
  n: 0.5,
  mu: 0.3,
  delta: 10.0,
};

// 计算卡片组件配置
const CalculationConfig = {
  key: 'PressureCoefficientCalculation',
  label: '洞顶回填土压力系数计算',
  formKey: 'cave-pressure-coefficient',
  initialValues: initialValues,
  
  // 动态计算类型选择逻辑
  calculationType: (values: FormValues): string => {
    if (values.burial_type === '深埋' && values.soil_mass === '无限土体') {
      return 'deep-infinite';
    } else if (values.burial_type === '浅埋' && values.soil_mass === '无限土体' && values.slope_direction === '上斜') {
      return 'qws';
    } else if (values.burial_type === '浅埋' && values.soil_mass === '无限土体' && values.slope_direction === '下斜') {
      return 'qwx';
    } else if (values.burial_type === '浅埋' && values.soil_mass === '有限土体' && values.slope_direction === '上斜') {
      return 'qys';
    } else if (values.burial_type === '浅埋' && values.soil_mass === '有限土体' && values.slope_direction === '下斜') {
      return 'qyx';
    }
    // 默认返回空，表示无计算
    return '';
  },
  
  // 结果格式化器
  resultFormatter: (data: any): ResultItem[] => {
    // 后端返回的结果包含lambda_value属性
    // 从不同可能的结构中提取lambda_value值
    const lambdaValue = typeof data === 'number' 
      ? data 
      : (data?.lambda_value || data?.data?.lambda_value || data?.results?.lambda_value || 0);
    return [{
      key: '0',
      name: 'λ（侧压力系数）',
      value: lambdaValue.toFixed(4),
      unit: ''
    }];
  },
  
  // 动态渲染表单字段
  renderFormFields: (burialType: string, soilMass: string, slopeDirection: string, handleBurialTypeChange: (value: string) => void, handleSoilMassChange: (value: string) => void, handleSlopeDirectionChange: (value: string) => void) => (
    <>
      {/* 通用选择字段 */}
      <Space orientation="vertical" style={{ width: '100%' }}>
        <Form.Item name="burial_type" label="埋置类型" required>
          <Select onChange={handleBurialTypeChange} style={{ width: 150 }}>
            <Option value="深埋">深埋</Option>
            <Option value="浅埋">浅埋</Option>
          </Select>
        </Form.Item>
        
        <Form.Item name="soil_mass" label="土体类型" required>
          <Select onChange={handleSoilMassChange} style={{ width: 150 }}>
            <Option value="有限土体">有限土体</Option>
            <Option value="无限土体">无限土体</Option>
          </Select>
        </Form.Item>
        
        {/* 只有浅埋时显示斜坡方向选择 */}
        {burialType === '浅埋' && (
          <Form.Item name="slope_direction" label="斜坡方向" required>
            <Select onChange={handleSlopeDirectionChange} style={{ width: 150 }}>
              <Option value="上斜">上斜</Option>
              <Option value="下斜">下斜</Option>
            </Select>
          </Form.Item>
        )}
        
        {/* 根据选择显示不同的参数字段 */}
        {(burialType === '深埋' && soilMass === '无限土体') && (
          // 深埋无限土体参数
          <NumberField name="varphi_c" label="计算内摩擦角φc (°)" required min={0} step={0.1} tooltip="溶洞充填物的计算内摩擦角" />
        )}
        
        {(burialType === '浅埋' && soilMass === '无限土体') && (
          // 浅埋无限土体参数
          <>
            <NumberField name="varphi_c" label="计算内摩擦角φc (°)" required min={0} step={0.1} tooltip="溶洞充填物的计算内摩擦角" />
            
            {/* 根据斜坡方向显示不同参数 */}
            {slopeDirection === '上斜' && (
              <NumberField name="alpha" label="充填物表面与水平面夹角α (°)" required min={0} step={0.1} tooltip="充填物表面与水平面的夹角" />
            )}
            
            {slopeDirection === '下斜' && (
              <>
              <NumberField name="alpha" label="充填物表面与水平面夹角α (°)" required min={0} step={0.1} tooltip="充填物表面与水平面的夹角" />
              <NumberField name="phi" label="竖向滑面摩擦角φ (°)" required min={0} step={0.1} tooltip="充填物竖向滑面的摩擦角" />
              </>
            )}
          </>
        )}
        
        {(burialType === '浅埋' && soilMass === '有限土体') && (
          // 浅埋有限土体参数
          <>
            <NumberField name="m" label="填充物表面坡率m" required min={0} step={0.1} tooltip="填充物表面的坡率" />
            <NumberField name="n" label="交叉点连线坡率n" required min={0} step={0.1} tooltip="溶洞壁隧道填充物表面交叉点连线坡率" />
            <NumberField name="mu" label="摩擦系数μ" required min={0} step={0.1} tooltip="溶腔壁充填物之间的摩擦系数" />
            <NumberField name="delta" label="侧向土压力与水平线夹角δ (°)" required min={0} step={0.1} tooltip="侧向土压力与水平线的夹角" />
          </>
        )}
        
        {/* 深埋有限土体提示 */}
        {(burialType === '深埋' && soilMass === '有限土体') && (
          <div style={{ color: '#ff4d4f', marginTop: 10 }}>
            注意：深埋有限土体目前没有计算方法
          </div>
        )}
      </Space>
    </>
  ),
};

// 计算卡片组件实现
const PressureCoefficientCard: React.FC = () => {
  // 用于控制动态表单显示的状态
  const [burialType, setBurialType] = useState(initialValues.burial_type);
  const [soilMass, setSoilMass] = useState(initialValues.soil_mass);
  const [slopeDirection, setSlopeDirection] = useState(initialValues.slope_direction);
  const [lastResults, setLastResults] = useState<ResultItem[] | null>(null);

  // 处理状态更新的函数
  const handleBurialTypeChange = (v: string) => {
    setBurialType(v);
    // 如果切换到深埋，重置斜坡方向
    if (v === '深埋') {
      setSlopeDirection('上斜');
    }
  };

  const handleSoilMassChange = (v: string) => {
    setSoilMass(v);
  };

  const handleSlopeDirectionChange = (v: string) => {
    setSlopeDirection(v);
  };

  // 根据当前状态获取对应的公式
  const getFormula = () => {
    if (burialType === '深埋' && soilMass === '无限土体') {
      return "\\lambda = \\tan^2\\left(45° - \\frac{\\varphi_c}{2}\\right)";
    } else if (burialType === '浅埋' && soilMass === '无限土体' && slopeDirection === '上斜') {
      return "\\lambda = \\frac{\\cos\\alpha - \\sqrt{\\cos^2\\alpha - \\cos^2\\varphi_c}}{\\cos\\alpha + \\sqrt{\\cos^2\\alpha - \\cos^2\\varphi_c}}";
    } else if (burialType === '浅埋' && soilMass === '无限土体' && slopeDirection === '下斜') {
      return "\\lambda = \\frac{\\tan\\theta}{\\tan(\\theta + \\varphi) \\times (1 + \\tan\\alpha \\times \\tan\\theta)}";
    } else if (burialType === '浅埋' && soilMass === '有限土体' && slopeDirection === '上斜') {
      return "\\lambda = \\frac{m \\times n}{m - n} \\times \\frac{1 - \\mu \\times n}{(\\mu + n) \\times \\cos\\delta + (1 - \\mu \\times n) \\times \\sin\\delta}";
    } else if (burialType === '浅埋' && soilMass === '有限土体' && slopeDirection === '下斜') {
      return "\\lambda = \\frac{m \\times n}{m + n} \\times \\frac{1 - \\mu \\times n}{(\\mu + n) \\times \\cos\\delta + (1 - \\mu \\times n) \\times \\sin\\delta}";
    }
    return "";
  };

  return (
    <StatefulCalculationCard
      title={CalculationConfig.label}
      formKey={CalculationConfig.formKey}
      initialValues={CalculationConfig.initialValues}
      renderFormFields={() => CalculationConfig.renderFormFields(burialType, soilMass, slopeDirection, handleBurialTypeChange, handleSoilMassChange, handleSlopeDirectionChange)}
      calculationType={(values) => CalculationConfig.calculationType(values)}
      resultFormatter={(data) => {
        const results = CalculationConfig.resultFormatter(data);
        setLastResults(results);
        return results;
      }}
      exportComponent={(form) => {
        const currentFormValues = form.getFieldsValue();
        const calculatedType = CalculationConfig.calculationType(currentFormValues);
        return (
          <ExportData
            siteName={CalculationConfig.label}
            inputs={currentFormValues}
            results={lastResults ? Object.fromEntries(lastResults.map(r => [r.key, r.value])) : {}}
            calculationType={calculatedType}
          />
        );
      }}
      columnCount={1} // 使用1列布局
      tableHeight={400} // 设置表格高度为400px
      formula={getFormula()}
      onAfterReset={(defaults: any) => {
        // 同步本地状态到默认值，确保条件渲染与公式更新
        setBurialType(defaults?.burial_type ?? initialValues.burial_type);
        setSoilMass(defaults?.soil_mass ?? initialValues.soil_mass);
        setSlopeDirection(defaults?.slope_direction ?? initialValues.slope_direction);
      }}
    />
  );
};

export default PressureCoefficientCard;